<?php
/**
 * [ Random Framework ]
 *
 * @version 2.0.0 (build 20130520)
 *
 * @link http://0x00.sinaapp.com/random.html
 * 
 * @author Coseylee (Coseylee@gmail.com).
 *
 */

class random_exception extends exception
{
	public $show_trace = true;

	public function __toString()
	{
		$this -> show_message();
	}

	public function show_message()
	{
		$debug_mode = $GLOBALS['RANDOM']['debug'] ? true : false;
		$debug_time = debug_time();
		$debug = array();

		// 跟踪信息
		foreach ($this -> getTrace() as $file)
		{
			$func = isset($file['class']) ? $file['class'] : '' ;
			$func .= isset($file['type']) ? $file['type'] : '' ;
			$func .= isset($file['function']) ? $file['function'] : '' ;
			//$func .= isset($file['args']) ? '('.implode(',', $file['args']).')' : '' ;
			$debug[] = '[Line: '.sprintf('%04d', isset($file['line']) ? $file['line'] : 0).'] '.str_replace(APP_ROOT, '', isset($file['file']) ? $file['file'] : '').' ('.$func.');';
		}
		
		// 未开启调试，写入日志并显示简要信息。
		if ($debug_mode === false)
		{
			$error_log = isset($GLOBALS['RANDOM']['debug_error_log']) ? $GLOBALS['RANDOM']['debug_error_log'] : false;
			if ($error_log !== false && is_writeable($error_log))
			{
				error_log('<?php exit(); ?>'.PHP_EOL.date('Y-m-d H:i:s').PHP_EOL.$this -> message.PHP_EOL.$this -> getTraceAsString().PHP_EOL.PHP_EOL, 3, $error_log);
			}

			$this -> message = 'Application Error';
			$this -> show_trace = false;
		}

		// 开启404后直接显示404
		if ($GLOBALS['RANDOM']['error_404'] == true)
		{
			$this -> not_found();
		}

		ob_end_clean();
		if ($GLOBALS['RANDOM']['gzip'])
		{
			if (function_exists('ob_gzhandler'))
			{
				ob_start('ob_gzhandler');
			}
			else
			{
				ob_start();
			}
		}
		include RANDOM_ROOT.'random.error_template.php';
		exit;
	}

	public function not_found()
	{
		header("HTTP/1.1 404 Not Found");
		if (file_exists($GLOBALS['RANDOM']['error_404_page']))
		{
			include $GLOBALS['RANDOM']['error_404_page'];
		}
		exit;
	}
}

class random_service_exception extends exception
{
	protected $data = array();

	public function __construct($error, $errno, $data = array())
	{
		parent::__construct($error, $errno);
		$this -> data = $data;
	}

	public function getData()
	{
		return $this -> data;
	}

	public function __toString()
	{
		return "Exception: [{$this -> code}]: {$this -> message}\n";
	}
}